# -*- coding: utf-8 -*-
# @Time    : 2023/5/5 10:29
# @Author  : Jonny
# @File    : LuckGitlabCodeReviewMain.py

from flask import Blueprint, request
import time
import json
from luck.core.LuckConstant import LuckConstant
from luck.ai.LuckGitlabCodeReviewService import LuckGitlabCodeReviewService
from luck.ai.LuckGitlabMergeCodeReviewService import LuckGitlabMergeCodeReviewService
from luck.ai.LuckGitlabCommitCodeReviewService import LuckGitlabCommitCodeReviewService

luck_gitlab_ai_bp = Blueprint('luck_gitlab_ai', __name__)


# 检查服务服务状态
@luck_gitlab_ai_bp.route('/gitlab/ai')
def index():
    return {
        "code": LuckConstant.CODE_SUCCESS,
        "data": [
            "/gitlab/ai",
            "/gitlab/ai/merge/code/review",
            "/gitlab/ai/commit/code/review",
            "/gitlab/ai/webhook"
        ],
        "msg": "gitlab_ai服务部署成功"
    }


chatgpt_openai_api_key = "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"  # 公司申请ChatGPT API key
# chatgpt_openai_api_key = "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"  # 个人申请ChatGPT API key
gitlab_private_token = "-sqvLoLAgfWHQ8NSQcqr"  # 公司私有化代码库Access Token
gitlab_server_url = "http://10.10.10.51"  # 公司私有化代码库
# gitlab_server_url = https://jihulab.com  # 极狐官网代码库

gitlab_project_id = "399"  # 项目id


# 合并代码review
@luck_gitlab_ai_bp.route('/gitlab/ai/merge/code/review', methods=['POST'])
def gitlab_ai_merge_code_review():
    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 开始 合并代码review')

    gitlab_merge_request_id = "5"  # 项目代码合并请求id
    obj = LuckGitlabMergeCodeReviewService(chatgpt_openai_api_key, gitlab_private_token, gitlab_server_url,
                                           gitlab_project_id, gitlab_merge_request_id)
    obj.start_review()  # 开始review
    obj.add_comment()  # 添加评论

    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 结束 合并代码review')


# 提交代码review
@luck_gitlab_ai_bp.route('/gitlab/ai/commit/code/review', methods=['POST'])
def gitlab_ai_commit_code_review():
    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 开始 提交代码review')

    gitlab_branch_name = "dev"  # backend_local
    obj = LuckGitlabCommitCodeReviewService(chatgpt_openai_api_key, gitlab_private_token, gitlab_server_url,
                                            gitlab_project_id, gitlab_branch_name)
    obj.start_review()  # 开始review
    obj.add_comment()  # 添加评论
    print(f'小程序 于 {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))} 结束 提交代码review')


@luck_gitlab_ai_bp.route('/gitlab/ai/webhook', methods=['POST'])
def gitlab_ai_webhook():
    post_data = json.loads(request.data)
    # print('post_data', post_data)
    """
    {
        'object_kind': 'push',
        'event_name': 'push',
        'before': 'edb661d15f4a7aa60313fb4e6b302a36879ae909',
        'after': 'f3c98b8b137e7fd0a9a7427f8958a142dbec3b7a',
        'ref ': 'refs/heads/dev',
        'checkout_sha ': 'f3c98b8b137e7fd0a9a7427f8958a142dbec3b7a ',
        'message ': None,
        'user_id ': 10,
        'user_name ': '侯良伟 ',
        'user_username ': 'houlw014',
        'user_email': '838608587@qq.com',
        'user_avatar': 'https://www.gravatar.com/avatar/634a6a3f374dc703177cc799f86cf8f8?s=80&d=identicon',
        'project_id': 399,
        'project': {
            'id': 399,
            'name': 'chatgpt-code-review-test',
            'description': '使用chatgpt对代码进行审查',
            'web_url ': 'http: //10.10.10.51/houlw014/chatgpt-code-review-test',
            'avatar_url ': None,
            'git_ssh_url ': 'git @10 .10 .10 .51: houlw014 / chatgpt - code - review - test.git ',
            'git_http_url ': 'http: //10.10.10.51/houlw014/chatgpt-code-review - test.git ',
            'namespace ': 'houlw014 ',
            'visibility_level ': 0,
            'path_with_namespace ': 'houlw014 / chatgpt - code - review - test ',
            'default_branch ': 'master ',
            'ci_config_path ': None,
            'homepage ': 'http: //10.10.10.51/houlw014/chatgpt-code-review-test',
            'url ': 'git @10 .10 .10 .51: houlw014 / chatgpt - code - review - test.git ',
            'ssh_url ': 'git @10 .10 .10 .51: houlw014 / chatgpt - code - review - test.git ',
            'http_url ': 'http: //10.10.10 .51 / houlw014 / chatgpt - code - review - test.git '
        },
        'commits': [{
            'id': 'f3c98b8b137e7fd0a9a7427f8958a142dbec3b7a',
            'message': 'test\n',
            'timestamp': '2023-05-04T15:31:54+08:00',
            'url': 'http://10.10.10.51/houlw014/chatgpt-code-review-test/commit/f3c98b8b137e7fd0a9a7427f8958a142dbec3b7a',
            'author ': {
                'name ': 'luck ',
                'email ': 'lwhou.hn @163.com '
            },
            'added ': [],
            'modified ': ['src / main / java / MapTest.java '],
            'removed ': []
        }],
        'total_commits_count ': 1,
        'repository ': {
            'name ': 'chatgpt-code-review-test',
            'url ': 'git @10.10.10.51:houlw014/chatgpt-code-review-test.git',
            'description ': '使用chatgpt对代码进行审查 ',
            'homepage ': 'http://10.10.10.51/houlw014/chatgpt-code-review-test',
            'git_http_url': 'http://10.10.10.51/houlw014/chatgpt-code-review-test.git ',
            'git_ssh_url ': 'git @10.10.10.51:houlw014/chatgpt-code-review-test.git ',
            'visibility_level ': 0
        }
    }
    """
    # path = '/home/www/test/'  # 项目目录
    return _hooks(post_data)


def _hooks(post_data):
    ref = post_data['ref']
    branch_name = ref.split('/')[-1]
    project_id = post_data["project"]["id"]
    commits = post_data["commits"]
    for commit in commits:
        obj = LuckGitlabCodeReviewService(chatgpt_openai_api_key, gitlab_private_token, gitlab_server_url, project_id,
                                          commit["id"])
        obj.start_review()  # 开始review
        obj.add_comment()  # 添加评论
